<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    div{
        width: 200px;
        height: 200px;
        background: cadetblue;
        position: absolute;
    }
    </style>
</head>
<body>
    <div></div>
    <script>
    var box=document.querySelector("div")    
    box.onmousedown=function(e){
      var e=e||window.event
      var box_x=e.offsetX;
      var box_y=e.offsetY;
      var maxwidth=document.documentElement.clientWidth-box.clientWidth
      var maxheight=document.documentElement.clientHeight-box.clientHeight
      document.onmousemove=function(e){
        box.style.left=e.pageX-box_x+"px"
        box.style.top=e.pageY-box_y+"px"
           if(e.pageX-box_x<=0){
            box.style.left=0
           }
           if(e.pageY-box_y<=0){
            box.style.top=0
           }
           if(e.pageX-box_x>=maxwidth){
            box.style.left=maxwidth+"px"
           }
           if(e.pageY-box_y>=maxheight){
            box.style.top=maxheight+"px"
           }   
      }
      document.onmouseup=function(){
        document.onmousemove=null;
        return false
    }
    } 
    </script>
</body>
</html>